<template>
  <div class="positions-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>职位管理</h1>
      <!-- PC端按钮 -->
      <el-button v-if="!isMobile" type="primary" @click="showAddDialog">添加职位</el-button>
    </div>
    
    <!-- 查询表单 -->
    <el-form :model="queryForm" ref="queryFormRef" :inline="true" class="query-form">
      <el-form-item label="职位名称">
        <el-input v-model="queryForm.positionName" placeholder="请输入职位名称" clearable />
      </el-form-item>
      <el-form-item label="所属部门">
        <el-input v-model="queryForm.department" placeholder="请输入所属部门" clearable />
      </el-form-item>
      <el-form-item label="职位级别">
        <el-select v-model="queryForm.positionLevel" placeholder="请选择职位级别" clearable>
          <el-option label="初级" value="初级" />
          <el-option label="中级" value="中级" />
          <el-option label="高级" value="高级" />
          <el-option label="资深" value="资深" />
          <el-option label="专家" value="专家" />
        </el-select>
      </el-form-item>
      <el-form-item label="招聘状态">
        <el-select v-model="queryForm.status" placeholder="请选择状态" clearable>
          <el-option label="招聘中" :value="2" />
          <el-option label="已结束" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 职位列表表格 -->
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="positionName" label="职位名称" />
      <el-table-column prop="department" label="所属部门" />
      <el-table-column prop="positionLevel" label="职位级别" />
      <el-table-column prop="headcount" label="招聘人数" width="100" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 2 ? 'success' : 'info'">
            {{ scope.row.status === 2 ? '招聘中' : '已结束' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryForm.pageNum"
        v-model:page-size="queryForm.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- PC端弹窗 -->
    <el-dialog
      v-if="!isMobile"
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加职位' : '编辑职位'"
      :width="isMobile ? '70%' : '50%'"
      class="position-dialog"
    >
      <el-form :model="positionForm" :rules="rules" ref="positionFormRef" label-width="100px">
        <!-- 职位名称 -->
        <el-form-item label="职位名称" prop="positionName">
          <el-input v-model="positionForm.positionName" placeholder="请输入职位名称，如：高级Java开发工程师" />
        </el-form-item>
        
        <!-- 所属部门 -->
        <el-form-item label="所属部门" prop="department">
          <el-input v-model="positionForm.department" placeholder="请输入所属部门" />
        </el-form-item>
        
        <!-- 职位级别 -->
        <el-form-item label="职位级别" prop="positionLevel">
          <el-select v-model="positionForm.positionLevel" placeholder="请选择职位级别" style="width: 100%">
            <el-option label="初级" value="初级" />
            <el-option label="中级" value="中级" />
            <el-option label="高级" value="高级" />
            <el-option label="资深" value="资深" />
            <el-option label="专家" value="专家" />
          </el-select>
        </el-form-item>
        
        <!-- 职位描述 -->
        <el-form-item label="职位描述" prop="jobDescription">
          <el-input 
            type="textarea" 
            v-model="positionForm.jobDescription" 
            :rows="4"
            placeholder="请输入职位详细描述，包括工作内容、职责等" 
          />
        </el-form-item>
        
        <!-- 任职要求 -->
        <el-form-item label="任职要求" prop="jobRequirements">
          <el-input 
            type="textarea" 
            v-model="positionForm.jobRequirements" 
            :rows="4"
            placeholder="请输入任职要求，包括学历、经验等硬性条件" 
          />
        </el-form-item>
        
        <!-- 所需技能 -->
        <el-form-item label="所需技能" prop="requiredSkills">
          <el-input 
            v-model="positionForm.requiredSkills" 
            placeholder="请输入所需技能，多个技能用逗号分隔" 
          />
        </el-form-item>
        
        <!-- 招聘人数 -->
        <el-form-item label="招聘人数" prop="headcount">
          <el-input-number 
            v-model="positionForm.headcount" 
            :min="1" 
            :max="100" 
            placeholder="请输入招聘人数" 
            style="width: 100%"
          />
        </el-form-item>

        <!-- 招聘状态 -->
        <el-form-item label="招聘状态" prop="status">
          <el-select v-model="positionForm.status" placeholder="请选择状态" style="width: 100%">
            <el-option label="招聘中" :value="2" />
            <el-option label="已结束" :value="3" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- App端悬浮按钮 -->
    <button v-if="isMobile" class="app-create-btn" @click="appDialogVisible = true">+ 创建角色</button>
    <!-- App端弹窗 -->
    <el-dialog
      v-if="isMobile"
      v-model="appDialogVisible"
      title="新建角色"
      width="90vw"
      class="app-position-dialog"
      :show-close="true"
    >
      <el-form :model="positionForm" :rules="rules" ref="positionFormRef" label-width="100px">
        <el-form-item label="职位名称" prop="positionName">
          <el-input v-model="positionForm.positionName" placeholder="请输入职位名称" />
        </el-form-item>
        <el-form-item label="职位级别" prop="positionLevel">
          <el-select v-model="positionForm.positionLevel" placeholder="请选择职位级别" style="width: 100%">
            <el-option label="初级" value="初级" />
            <el-option label="中级" value="中级" />
            <el-option label="高级" value="高级" />
            <el-option label="资深" value="资深" />
            <el-option label="专家" value="专家" />
          </el-select>
        </el-form-item>
        <el-form-item label="招聘人数" prop="headcount">
          <el-input-number v-model="positionForm.headcount" :min="1" :max="100" placeholder="请输入招聘人数" style="width: 100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="appDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

// 控制弹窗显示/隐藏
const dialogVisible = ref(false)
// 弹窗类型：add-添加，edit-编辑
const dialogType = ref('add')
// 表单引用
const positionFormRef = ref(null)

// 职位表单数据
const positionForm = reactive({
  id: null,              // 职位ID
  positionName: '',      // 职位名称
  department: '',        // 所属部门
  positionLevel: '',     // 职位级别
  jobDescription: '',    // 职位描述
  jobRequirements: '',   // 任职要求
  requiredSkills: '',    // 所需技能
  headcount: 1,         // 招聘人数
  status: 2            // 招聘状态
})

// 表单验证规则
const rules = {
  positionName: [
    { required: true, message: '请输入职位名称', trigger: 'blur' }
  ],
  department: [
    { required: true, message: '请输入所属部门', trigger: 'blur' }
  ],
  positionLevel: [
    { required: true, message: '请选择职位级别', trigger: 'change' }
  ],
  jobDescription: [
    { required: true, message: '请输入职位描述', trigger: 'blur' }
  ],
  jobRequirements: [
    { required: true, message: '请输入任职要求', trigger: 'blur' }
  ],
  headcount: [
    { required: true, message: '请输入招聘人数', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择招聘状态', trigger: 'change' }
  ]
}

// 查询表单数据
const queryForm = reactive({
  positionName: '',
  department: '',
  positionLevel: '',
  status: null,
  pageNum: 1,
  pageSize: 10,
  isPaged: true
})

// 表格数据
const tableData = ref([])
const total = ref(0)
const queryFormRef = ref(null)

// 添加移动端检测
const isMobile = computed(() => {
  return window.innerWidth <= 768
})

// 监听窗口大小变化
window.addEventListener('resize', () => {
  isMobile.value = window.innerWidth <= 768
})

// 查询职位列表
const handleQuery = async () => {
  try {
    const response = await request.post('/api/positions/query', queryForm)
    if (response.code === 200) {
      tableData.value = response.data.records
      total.value = response.data.total
    } else {
      ElMessage.error(response.msg || '查询失败')
    }
  } catch (error) {
    ElMessage.error('查询失败，请稍后重试')
    console.error('查询职位失败:', error)
  }
}

// 重置查询条件
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  queryForm.pageNum = 1
  handleQuery()
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  queryForm.pageSize = val
  handleQuery()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  queryForm.pageNum = val
  handleQuery()
}

// 显示添加职位弹窗
const showAddDialog = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
  // 重置表单
  resetForm()
}

// 显示编辑职位弹窗
const handleEdit = (row) => {
  dialogType.value = 'edit'
  dialogVisible.value = true
  // 填充表单数据
  Object.keys(positionForm).forEach(key => {
    positionForm[key] = row[key]
  })
}

// 重置表单
const resetForm = () => {
  if (positionFormRef.value) {
    positionFormRef.value.resetFields()
  }
  Object.keys(positionForm).forEach(key => {
    positionForm[key] = key === 'headcount' ? 1 : key === 'status' ? 2 : ''
  })
  positionForm.id = null
}

// 提交表单
const handleSubmit = async () => {
  if (!positionFormRef.value) return
  
  // 表单验证
  await positionFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let response
        if (dialogType.value === 'add') {
          // 添加职位
          response = await request.post('/api/positions/add', positionForm)
        } else {
          // 更新职位
          response = await request.post('/api/positions/update', positionForm)
        }
        
        if (response.code === 200) {
          ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
          dialogVisible.value = false
          handleQuery() // 刷新列表
        } else {
          ElMessage.error(response.msg || (dialogType.value === 'add' ? '添加失败' : '更新失败'))
        }
      } catch (error) {
        ElMessage.error(dialogType.value === 'add' ? '添加失败，请稍后重试' : '更新失败，请稍后重试')
        console.error(dialogType.value === 'add' ? '添加职位失败:' : '更新职位失败:', error)
      }
    }
  })
}

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该职位吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await request.delete(`/api/positions/delete/${row.id}`)
      if (response.code === 200) {
        ElMessage.success('删除成功')
        await handleQuery()
      } else {
        ElMessage.error(response.msg || '删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败，请稍后重试')
      console.error('删除职位失败:', error)
    }
  }).catch(() => {})
}

// 页面加载时执行查询
onMounted(() => {
  handleQuery()
})

const appDialogVisible = ref(false)
</script>

<style scoped>
.positions-container {
  padding: 24px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.positions-container h1 {
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 0;
  position: relative;
  padding-left: 16px;
}

.positions-container h1::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 24px;
  background-color: #409eff;
  border-radius: 2px;
}

.query-form {
  margin-bottom: 24px;
  padding: 24px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.query-form :deep(.el-form-item) {
  margin-bottom: 16px;
}

.query-form :deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

.query-form :deep(.el-input__wrapper),
.query-form :deep(.el-select) {
  width: 240px;
}

.operation-area {
  margin-bottom: 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.operation-area .el-button {
  padding: 12px 24px;
  font-weight: 500;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

:deep(.el-table th) {
  background-color: #f5f7fa !important;
  font-weight: 600;
  color: #1f2937;
  height: 50px;
}

:deep(.el-table td) {
  padding: 16px 0;
}

:deep(.el-table .cell) {
  line-height: 1.5;
}

:deep(.el-tag) {
  border-radius: 4px;
  padding: 0 12px;
  height: 24px;
  line-height: 24px;
  font-weight: 500;
}

:deep(.el-button--link) {
  font-weight: 500;
  padding: 4px 8px;
}

:deep(.el-button--link.el-button--primary) {
  color: #409eff;
}

:deep(.el-button--link.el-button--danger) {
  color: #f56c6c;
}

.pagination-container {
  margin-top: 24px;
  padding: 16px 0;
  display: flex;
  justify-content: flex-end;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

:deep(.el-dialog) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-dialog__header) {
  margin: 0;
  padding: 20px 24px;
  border-bottom: 1px solid #e4e7ed;
  background-color: #f5f7fa;
}

:deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
}

:deep(.el-dialog__body) {
  padding: 24px;
}

:deep(.el-dialog__footer) {
  padding: 16px 24px;
  border-top: 1px solid #e4e7ed;
  background-color: #f5f7fa;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-input__wrapper),
:deep(.el-select),
:deep(.el-input-number) {
  width: 100%;
}

:deep(.el-textarea__inner) {
  font-family: inherit;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.dialog-footer .el-button {
  padding: 12px 24px;
  font-weight: 500;
}

/* 添加一些动画效果 */
:deep(.el-button) {
  transition: all 0.3s ease;
}

:deep(.el-button:hover) {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

:deep(.el-table__row) {
  transition: all 0.3s ease;
}

:deep(.el-table__row:hover) {
  background-color: #f5f7fa !important;
}

/* 响应式布局 */
@media screen and (max-width: 768px) {
  .positions-container {
    padding: 12px;
  }

  .query-form {
    padding: 12px;
  }

  .query-form :deep(.el-form-item) {
    margin-bottom: 12px;
  }

  .query-form :deep(.el-input__wrapper),
  .query-form :deep(.el-select) {
    width: 100%;
  }

  .operation-area {
    flex-direction: column;
    gap: 12px;
  }

  .operation-area .el-button {
    width: 100%;
  }

  .position-dialog :deep(.el-dialog) {
    max-width: 70vw !important;
    max-height: 60vh !important;
    overflow-y: auto !important;
    top: 10px !important;
    margin: 0 auto !important;
    transform: none !important;
  }

  .position-dialog :deep(.el-dialog__body) {
    padding: 8px;
  }

  .position-dialog :deep(.el-form-item) {
    margin-bottom: 6px !important;
  }

  .position-dialog :deep(.el-form-item__label) {
    float: none;
    display: block;
    text-align: left;
    padding: 0 0 8px;
  }

  .position-dialog :deep(.el-form-item__content) {
    margin-left: 0 !important;
  }

  .position-dialog :deep(.el-input__wrapper),
  .position-dialog :deep(.el-select),
  .position-dialog :deep(.el-input-number) {
    width: 100%;
  }

  .dialog-footer {
    flex-direction: column;
    gap: 8px;
  }

  .dialog-footer .el-button {
    width: 100%;
  }

  .app-create-btn {
    position: fixed;
    right: 16px;
    bottom: 32px;
    z-index: 9999;
    background: #409eff;
    color: #fff;
    border: none;
    border-radius: 50px;
    padding: 14px 28px;
    font-size: 18px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.15);
  }
  .app-position-dialog :deep(.el-dialog) {
    top: 10px !important;
    max-width: 90vw !important;
    max-height: 70vh !important;
    margin: 0 auto !important;
    transform: none !important;
  }
  .app-position-dialog :deep(.el-dialog__body) {
    padding: 8px;
  }
  .app-position-dialog :deep(.el-form-item) {
    margin-bottom: 6px !important;
  }
}

.page-header .el-button {
  padding: 12px 24px;
  font-weight: 500;
  height: 40px;
}
</style> 